package com.http.intg;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.util.concurrent.FailureCallback;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.SuccessCallback;
import org.springframework.web.client.AsyncRestTemplate;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class AsyncHttpServiceClient {
    public static final Logger log = LoggerFactory.getLogger(AsyncHttpServiceClient.class);

    private AsyncRestTemplate asyncRestTemplate;

    public static final String GET_HTTP_RESOURCE_PATH = "http://localhost:8081/user/queryUserById/{id}";

    public String getUserById(int id) throws IOException {
        log.info("Start");
        ListenableFuture<ResponseEntity<String>> entity = asyncRestTemplate.getForEntity(GET_HTTP_RESOURCE_PATH, String.class, id);
        entity.addCallback(new SuccessCallback<ResponseEntity<String>>() {
            @Override
            public void onSuccess(ResponseEntity<String> result) {
                log.info(result.getBody());
                log.info("A");
            }
        }, new FailureCallback() {
            @Override
            public void onFailure(Throwable ex) {
                log.error(ex.getMessage());
                log.info("B");
            }
        });
        log.info("C");
        //测试readtimeout
//        try {
//            TimeUnit.SECONDS.sleep(40000); // 暂停40秒
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        return "End";
    }

    /**
     * @Description: The asyncRestTemplate to set
     * @param asyncRestTemplate
     */
    public void setAsyncRestTemplate(final AsyncRestTemplate asyncRestTemplate){this.asyncRestTemplate = asyncRestTemplate;}
}
